<?php
/**
* phpCan - http://idc.anavallasuiza.com/
*
* phpCan is released under the GNU Affero GPL version 3
*
* More information at license.txt
*/

defined('ANS') or die();

class Cache {
	private $Debug;

	public function __construct () {
		global $Debug;

		$this->Debug = $Debug;
	}


	/**
	 * private function folder ([string $subfolder])
	 *
	 * return string
	 */
	private function folder ($subfolder = '') {
		return filePath('phpcan/cache|'.$subfolder).'/';
	}

	/**
	 * public function save (string $name, mixed $data, [string $subfolder])
	 *
	 * save data in cache
	 *
	 * return boolean
	 */
	public function save ($name, $data, $subfolder = '') {
		if (!$data) {
			return false;
		}

		$name = alphaNumeric($name, true);

		$dir = $this->folder($subfolder);

		if (!is_dir($dir) && !is_writable(dirname($dir))) {
			return false;
		} else if (!is_dir($dir)) {
			mkdir($dir, 0755);
		}

		$data = serialize($data);

		if (file_put_contents($dir.$name, $data)) {
			return true;
		}

		return false;
	}


	/**
	 * public function load (string $name, [int $time], [string $subfolder])
	 *
	 * load data saved in cache
	 *
	 * return false/mixed
	 */
	public function load ($name, $time = 0, $subfolder = '') {
		$name = alphaNumeric($name, true);

		$filename = $this->folder($subfolder).$name;

		if (!is_file($filename)) {
			return false;
		}

		if ($time && filemtime($filename) > time() + $time) {
			return false;
		}

		$data = file_get_contents($filename);

		return unserialize($data);
	}


	/**
	 * public function saveFile (string $filename, [string $subfolder])
	 *
	 * save a file in cache
	 *
	 * return boolean
	 */
	public function saveFile ($filename, $subfolder = '') {
		$name = alphaNumeric($filename, true);

		$File = new \files\File;

		return $File->save($filename, $this->folder($subfolder), $name);
	}


	/**
	 * public function loadFile (string $file, [int $time], [string $subfolder])
	 *
	 * load file saved in cache
	 *
	 * return false/string
	 */
	public function loadFile ($file, $time = 0, $subfolder = '') {
		$file = alphaNumeric($file, true);

		$filename = $this->folder($subfolder).$file;

		if (!is_file($filename)) {
			return false;
		}

		if ($time && filemtime($filename) > time() + $time) {
			return false;
		}

		return $filename;
	}
}
?>
